import React, { Component } from 'react'
import { connect } from 'dva';
import { Table, Button, Drawer } from 'antd';

import { UmiComponentProps, BaseComponentProps, Filds } from '@/common/type'
import { ColumnProps } from 'antd/es/table';

import Form from './ToDoSearchForm';
import Details from '../details';
import Ellipsis from '@/components/Ellipsis';
import { MyIcon } from '@/components/MyIcon';

import { Span } from '../styled'
import { KEYS_COUNT } from '../enum';

import { checkInit } from '@/utils/util';

interface IData {
  id: string;
  name: string;
  position: string;
  originTypeName: string;
  userName: string;
  state: number;
  overdueName: string;
  buildName: string;
  floorName: string;
  areaName: string;
}

interface IDetails {
  level: Array<string>;
}
export interface P {
  list?: {
    data: Array<IData>,
    dataCnt: number,
  },
  details?: IDetails;
  stateCount?: {
    countData: {

    }
  };
}

interface State {
  current: number;
  showInfo: boolean;
}


const CountComponent = (props) => {
  const values = KEYS_COUNT.map(v => ({
    ...v,
    value: props.countData[v.key]
  }))

  return (
    <div style={{ display: 'flex', width: 1113, justifyContent: 'space-around', paddingTop: '10px', margin: '0 auto' }}>
      {
        Array.isArray(values) && values.map((v, ind) => (
          <div key={v.name} style={{ width: '195px', borderRight: `${ind !== values.length - 1 ? '1px solid #CCCCCC' : 0} ` }}>
            <MyIcon icon={v.icon} style={{ color: v.color, fontSize: 18 }} />
            <Span color={v.color}>{v.name || ''}：{v.value || 0}</Span>
          </div>
        ))
      }
    </div>
  )
}

type Props = P & UmiComponentProps & BaseComponentProps;

@connect(({ risk, loading }) => ({
  list: risk.todoList || {},
  stateCount: risk.stateCount,
  details: risk.details || {},
  dict: risk.dict,
  cond: risk.todoCond,
  // buttons: menu.buttons,
  loading: loading.effects['risk/queryTodoPage']
}))
class Todo extends Component<Props, State> {

  state: State = {
    current: 1,
    showInfo: false,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'risk/queryStateCount' })
    checkInit() ? dispatch({ type: `risk/queryTodoPage` }) : this.queryData();
  }
  private handleDetails = (id) => {

    const { dispatch } = this.props;
    dispatch({ type: 'risk/queryInfoById', payload: { recordId: id } }).then((res) => {
      this.setState({ showInfo: true })
    })
  }
  private queryData(offset = 1) {
    const { dispatch } = this.props;

    dispatch({
      type: 'risk/queryTodoPage',
      payload: {
        pageNum: offset
      },
    });
  }

  private initCurrent = () => {
    this.setState({ current: 1 })
  }

  private onShowSizeChange = (current: number, pageSize: number) => {
    const { dispatch, cond } = this.props;
    cond.pageSize = pageSize;
    dispatch({ type: `risk/updateTodoCond`, payload: cond })
  }

  render() {
    const { buttons } = this.props;
    const btnList: Filds = {};
    if (Array.isArray(buttons)) {
      buttons.forEach(item => {
        btnList[item.name] = item.name
      });
    }
    //table表格数据
    const { data = [], dataCnt } = this.props.list;
    //隐患统计数据
    const { countData = {} } = this.props.stateCount;

    const pagination = {
      total: dataCnt,
      showTotal: (total: number) => `共 ${total} 条`,
      current: this.state.current,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      onShowSizeChange: this.onShowSizeChange,
      onChange: (current: number) => {
        this.setState({ current }, () => this.queryData(current));
        this.queryData(current)
      },
    };

    const ans = Array.isArray(data) ? data.map((v, index) => ({ ...v, ind: index + 1 < 10 ? `0${index + 1}` : index + 1 })) : [];

    const columns: ColumnProps<IData>[] = [{
      title: '序号',
      dataIndex: 'ind',
    }, {
      title: '设备设施名称',
      dataIndex: 'name',
    }, {
      title: '设备位置',
      dataIndex: 'buildName',
      render: (text, record) => (
        <Ellipsis tooltip={true} lines={1}>
          {record.buildName || ''}{record.floorName || ''}{record.areaName || ''}
        </Ellipsis>
      )
    }, {
      title: '隐患来源',
      dataIndex: 'originTypeName',
    }, {
      title: '处理人',
      dataIndex: 'userName',
    }, {
      title: '处理状态',
      dataIndex: 'stateName',
    }, {
      title: '是否逾期',
      dataIndex: 'overdueName',
    }, {
      title: '操作', key: 'x', render: (record: IData) => {
        return (
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <Button style={{ padding: 0, textAlign: 'start' }} type="link" onClick={() => this.handleDetails(record.id)}>详情</Button>
          </div>
        )
      }
    }];
    return (
      <>
        <CountComponent countData={countData} />
        <Form current={this.state.current} initCurrent={this.initCurrent} new={!!btnList['新增']} />
        <Table
          columns={columns}
          pagination={pagination}
          dataSource={ans}
          bordered
          loading={this.props.loading}
          rowKey="id"
        />
        <Drawer
          title="隐患详情"
          placement="right"
          closable={true}
          width={900}
          onClose={() => this.setState({ showInfo: false })}
          visible={this.state.showInfo}
          destroyOnClose={true}
        >
          <Details data={this.props.details} />
        </Drawer>
      </>

    );
  }
}

export default Todo;
